<?php
namespace App\Repositories\User;

use App\Exceptions\OrdinaryException;
use App\Repositories\BaseRepository;
use App\Models\User\Users;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Traits\Third\TokenThird;
use App\Repositories\System\MessageRepository;
use Crypt;

class Author2Repository extends BaseRepository {
    use TokenThird;

    private $_keys;

    public function __construct()
    {
        parent::__construct();
        $this->_keys = $this->model->getKeyName();
    }

    public function model()
    {
        // TODO: Implement model() method.
        return Users::class;
    }

    /**
     * 通过第三方登录标识查询用户
     *
     * @param string $openId
     * @param string $state 来源
     * @param string 微信唯一标识
     * @author zx
     * @date 2018-11-19
     */
    public function getUserInfoByOpenId(string $openId, string $state, string $unionId='', array $info=[])
    {
        try{
            $res = $this->where($state."_openid", $openId)->first();
            if ($unionId && isset($res->id) && $res->{$this->_keys} && !$res->wxunionid) {
                $params = [
                    'unionid' => $unionId
                ];
                $res = $this->updateByPrimary($res->{$this->_keys}, $params);
            }
        } catch (ModelNotFoundException $exception) {
            $func = function()use($state, $openId, $unionId, &$res, $info){
                $data[$state . "_openid"] = $openId;
                $data['nickname'] = $info['nickname']??'';
                $data['headimg'] = $info['image']??'';
                $data['sex'] = $info['sex']??0;
                $data['number'] = $this->getNumbers();
                $data['unionid'] = $unionId;
                $data['password'] = Crypt::encrypt("123456");
                $res = $this->create($data);
                if (!isset($res->id) || !$res->id) {
                    $res = FALSE;
                } else {
                    $messages = new MessageRepository();
                    $cdnName = config("system.cdn_name");
                    $contents = "恭喜您已成功注册{$cdnName}会员!\n会员账户:{$data['number']}。\n会员初始密码:123456。\n可通过手机号,邮箱,账户进行登录操作\n希望我们的产品对您有所帮助!祝您使用愉快!";
                    $messages->addMessages($res->id, "恭喜您注册成功!", $contents);
                }
            };
            try{
                if ($unionId) {
                    $res = $this->where("unionid", $unionId)->first();
                    if (isset($res->{$this->_keys}) && $res->{$this->_keys} && !$res->$state."_openid") {
                        $lists = [
                            $state."_openid" => $openId
                        ];
                        $res = $this->updateByPrimary($res->{$this->_keys}, $lists);
                    }
                }else{
                    $func();
                }
            } catch (ModelNotFoundException $exception) {
                $func();
            }
        }
        return $res??FALSE;
    }

    /**
     * 手机邮箱注册操作
     *
     * @param array $param 注册账户密码
     * @param string $field 字段
     * @author zx
     * @date 2018-11-23
     */
    public function register(array $param, string $field)
    {
        try{
            $res = $this->where($field, $param['number'])->first();
            if($res){
                throw new OrdinaryException("账户已存在");
            }
        } catch (ModelNotFoundException $exception) {
            $data[$field] = $param['number'];
            $data['password'] = Crypt::encrypt($param['password']);
            $data['number'] = $this->getNumbers();
            $data['nickname'] = $param['nickname'];
            $data['lon'] = $param['lon']??'';
            $data['lat'] = $param['lat']??'';
            $res = $this->create($data);
            if(isset($res->{$this->_keys}) && $res->{$this->_keys}){
                return $res;
            }
        }
        throw new OrdinaryException("注册失败");
    }

    /**
     * 手机号码邮箱账号登录操作
     *
     * @param array $param 登录账户密码
     * @param string $field 字段
     * @author zx
     * @date 2018-11-23
     */
    public function login(array $param, string $field)
    {
        try{
            $res = $this->where($field, $param['number'])
                ->first();
            if(isset($res->{$this->_keys}) && $res->{$this->_keys} && $param['password'] == Crypt::decrypt($res->password)){
                if(isset($param['lon']) && isset($param['lat'])){
                    $this->updateByPrimary($res->{$this->_keys}, ['lon'=>$param['lon'],'lat'=>$param['lat']]);
                }
                return $res?(@$res->toArray()?:[]):[];
            }
            return [];
        } catch (ModelNotFoundException $exception) {
            throw new OrdinaryException("登录失败,账号或密码错误");
        }
    }

    /**
     * 完善信息操作
     *
     * @param array $param 信息
     * @param int $uid 用户ID
     * @author zx
     * @date 2019-01-10
     */
    public function addUserInfo(array $param, int $uid)
    {
        $keys = $this->model->getKeyName();
        $data = [];
        if( isset($param['nickname']) && $param['nickname'] ) $data['nickname'] = $param['nickname'];
        if( isset($param['password']) && $param['password'] ) $data['password'] = $param['password'];
        if( isset($param['image']) && $param['image'] ) $data['headimg'] = $param['image'];
        if( isset($param['sex']) && ($param['sex'] || $param['sex'] === 0 || $param['sex'] === '0') ) $data['sex'] = $param['sex'];
        if( isset($param['prov']) && $param['prov'] ) $data['prov'] = $param['prov'];
        if( isset($param['city']) && $param['city'] ) $data['city'] = $param['city'];
        if( isset($param['area']) && $param['area'] ) $data['area'] = $param['area'];
        if( isset($param['lon']) && $param['lon'] ) $data['lon'] = $param['lon'];
        if( isset($param['lat']) && $param['lat'] ) $data['lat'] = $param['lat'];
        try{
            $udata = $this->where("id", $uid)->first();
            $list = [];
            if(isset($data['nickname']) && $data['nickname'] && $udata->nickname != $data['nickname']) $list['nickname'] = $data['nickname'];
            if(isset($data['password']) && $data['password'] && $udata->password != Crypt::encrypt($data['password'])) $list['password'] = Crypt::encrypt($data['password']);
            if(isset($data['headimg']) && $data['headimg'] && !$udata->headimg) $list['headimg'] = $data['headimg'];
            if(isset($data['sex']) && ($data['sex'] || $data['sex'] === 0 || $data['sex'] === '0' ) && $udata->sex != $data['sex']) $list['sex'] = $data['sex'];
            if(isset($data['prov']) && $data['prov'] && $udata->prov != $data['prov']) $list['prov'] = $data['prov'];
            if(isset($data['city']) && $data['city'] && $udata->city != $data['city']) $list['city'] = $data['city'];
            if(isset($data['area']) && $data['area'] && $udata->area != $data['area']) $list['area'] = $data['area'];
            if(isset($data['lon']) && $data['lon'] && $udata->lon != $data['lon']) $list['lon'] = $data['lon'];
            if(isset($data['lat']) && $data['lat'] && $udata->lat != $data['lat']) $list['lat'] = $data['lat'];
            if($list){
                $res = $this->updateByPrimary($uid, $list);
                if($res->$keys) return $res?(@$res->toArray()?:[]):[];
            } else {
                return $udata?(@$udata->toArray()?:[]):[];
            }
            return [];
        } catch (ModelNotFoundException $exception) {
            throw new OrdinaryException("用户不存在", 500);
        }
    }

    /**
     * 编辑头像
     *
     * @param array $param 信息
     * @param int $uid 用户ID
     * @author zx
     * @date 2019-01-23
     */
    public function uploadHeadImg(array $param, int $uid)
    {
        $data = $list = [];
        if( isset($param['image']) && $param['image'] ) $data['headimg'] = $param['image'];
        try {
            $udata = $this->where("id", $uid)->first();
            if(isset($data['headimg']) && $data['headimg'] && $udata->headimg != $data['headimg']) $list['headimg'] = $data['headimg'];
            if($list){
                $res = $this->updateByPrimary($uid, $list);
                if($res->id) return $res?(@$res->toArray()?:[]):[];
            } else {
                return $udata?(@$udata->toArray()?:[]):[];
            }
            return [];
        } catch (ModelNotFoundException $exception) {
            throw new OrdinaryException("用户不存在", 500);
        }
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }

}